<template>
  <div class="app-container">
    <el-dialog
      title="请选择导出数据的方式"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="500px"
    >
      <el-form ref="form" label-width="100px">
        <el-form-item label="导出方式">
          <el-radio-group v-model="exMode">
            <el-radio :label="1">勾选导出</el-radio>
            <el-radio :label="2">按条件导出</el-radio>
<!--            <el-radio :label="3">全部导出</el-radio>-->
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="exportData()">提 交</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
        </span>
    </el-dialog>
    <div ref="filter" class="filter-container" style="margin-bottom: unset;">
      <el-input
        v-model="listQuery.name"
        size="small"
        placeholder="请填写标题"
        style="width: 200px;margin-left:5px"
        class="filter-item filter-left"
        clearable
      />
      <el-select
        v-model="listQuery.type"
        class="filter-left"
        placeholder="请选择类型"
        clearable
        filterable
        size="small"
      >
        <el-option v-for="item in typeOption" :label="item.label" :value="item.value"/>
      </el-select>
      <date-selector v-model="listQuery.updatedAt" style="width: 250px"/>
      <el-button
        size="small"
        class="filter-item filter-left"
        icon="el-icon-search"
        type="primary"
        style="margin-left:5px"
        plain
        @click="search()"
      />
      <!--        搜索-->
      <!--      </el-button>-->
    </div>
    <div ref="filter" class="filter-container">
      <el-button
        size="small"
        class="filter-item left"
        type="primary"
        style="margin-left: 5px;"
        icon="el-icon-plus"
        @click="addRow()"
        v-if="isMy"
      >
        新建
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        type="warning"
        style="margin-left: 5px;"
        icon="el-icon-s-grid"
        @click="setCustomerGroupCollect"
        v-if="isMy || isIntention"
      >
        设置分组
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        type="danger"
        style="margin-left: 5px;"
        icon="el-icon-price-tag"
        @click="setCustomerLabelCollect"
        v-if="isMy || isIntention"
      >
        设置标签
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        type="info"
        style="margin-left: 5px;"
        icon="el-icon-paperclip"
        @click="setCustomerSourceCollect"
        v-if="isMy || isIntention"
      >
        设置来源
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        type="warning"
        style="margin-left: 5px;"
        icon="el-icon-star-on"
        @click="setCustomerIntentionCollect"
        v-if="isMy || isIntention"
      >
        批量更新意向状态
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        type="primary"
        style="margin-left: 5px;"
        icon="el-icon-star-on"
        @click="setCustomerEmailCollect"
        v-if="isMy || isIntention"
      >
        新增营销任务
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        type="danger"
        style="margin-left: 5px;"
        icon="el-icon-delete"
        @click="batchDeleteBlock"
        v-if="isMy || isIntention"
      >
        数据删除
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        style="margin-left: 5px;"
        type="warning"
        icon="el-icon-upload2"
        @click="openExportCustomer()"
        v-if="(isMy || isIntention) && $common.IsInExe()"
      >
        导出
      </el-button>
      <el-button
        size="small"
        class="filter-item left"
        style="margin-left: 5px;"
        type="success"
        icon="el-icon-collection"
        @click="downloadExportTemplate()"
        v-if="(isMy || isIntention) && $common.IsInExe()"
      >
        下载导入模板
      </el-button>
      <!--      <el-button-->
      <!--        size="small"-->
      <!--        class="filter-item left"-->
      <!--        style="margin-left: 5px;"-->
      <!--        icon="el-icon-s-unfold"-->
      <!--        @click="setCustomerIsPrivateCollect(0)"-->
      <!--        v-if="isMy || isIntention"-->
      <!--      >-->
      <!--        批量移入公海-->
      <!--      </el-button>-->
      <!--      <el-button-->
      <!--        size="small"-->
      <!--        class="filter-item left"-->
      <!--        style="margin-left: 5px;"-->
      <!--        icon="el-icon-s-fold"-->
      <!--        @click="setCustomerIsPrivateCollect(1)"-->
      <!--        v-if="isWater"-->
      <!--      >-->
      <!--        批量认领客户-->
      <!--      </el-button>-->
      <el-button
        size="small"
        class="filter-item left"
        style="margin-left: 5px;"
        type="warning"
        icon="el-icon-upload2"
        @click="importCustomer()"
        v-if="isMy  && $common.IsInExe()"
      >
        导入
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      border
      size="medium"
      :height="tableHeight"
      :header-cell-style="{background: '#F2F6FC'}"
      @selection-change="handleSelection"
      class="customer"
    >
      <el-table-column type="selection" align="center"/>
      <el-table-column align="center" width="100" label="序号" type="index"/>
      <el-table-column align="center" label="类型" width="120" prop="type" show-overflow-tooltip>
        <template slot-scope="{row}">
          <template v-if="row.from == 0">外部导入</template>
          <template v-else-if="row.from == 1">全球搜索</template>
          <template v-else>数据营销</template>
        </template>
      </el-table-column>
      <el-table-column align="center" label="分组" width="150" prop="diyGroupId" show-overflow-tooltip>
        <template slot-scope="{row}">
          {{row.diyGroup ? row.diyGroup.name : '未分组'}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="来源" width="150" prop="sourceId" show-overflow-tooltip>
        <template slot-scope="{row}">
          {{row.source ? row.source.name : '无'}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="标签" width="180" type="index">
        <template slot-scope="{row}">
          <template v-if="row.labels">
            <template v-for="(v,k) in row.labels" style="margin-bottom: 2px">
              <el-tag
                :style="{'background-color': v.color,'border-color': v.color}"
                size="mini"
                effect="dark">
                {{ v.name }}
              </el-tag>
            </template>
          </template>
          <template v-else>无</template>
        </template>
      </el-table-column>
      <el-table-column align="center" label="标题" prop="name"/>
      <el-table-column align="center" label="域名" min-width="75">
        <template slot-scope="{row}">
          <template v-if="row.url && row.domain">
            <el-link target="_blank" :href="row.url">{{ row.domain }}</el-link>
          </template>
          <template v-else>
            无
          </template>
        </template>
      </el-table-column>
      <el-table-column align="center" label="描述">
        <template slot-scope="{row}">
          {{row.desc ? row.desc : '无'}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="归属人" v-if="currentUserInfo.userType == 3">
        <template slot-scope="{row}">
          {{row.user ? row.user.trueName : '无'}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" prop="belongAt" show-overflow-tooltip>
        <el-table-column align="center" label="最后操作时间" prop="followMessage" show-overflow-tooltip>
          <template slot-scope="{row}">
            {{row.createdAt}}
            <el-divider></el-divider>
            {{row.updatedAt}}
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column align="center" width="250" label="操作">
        <template slot-scope="{row}">
          <template v-if="currentUserInfo.userType == 3 || row.userId == currentUserInfo.userId">
            <el-button-group>
              <el-button type="success" plain size="mini" @click="customerInfo(row.id,row.from)">
                查看详情
              </el-button>
              <el-button type="primary" plain size="mini" @click="editRow(row.id)">
                编辑
              </el-button>
              <el-button type="danger" plain size="mini" @click="deleteRow(row.id)">
                删除
              </el-button>
            </el-button-group>
          </template>
          <template v-else>
            <el-button type="success" plain size="mini" @click="customerInfo(row.id,row.from)">
              查看详情
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="fetchData"
    />
    <block-drawer :id="blockId" :source="blockFrom" :action="listQuery.action" :show.sync="showCustomersState"
                 @closeAction="refresh"/>
    <group :id="collectId" :show.sync="showGroupState" :source="source" @closeAction="refresh"/>
    <intention :id="collectId" :show.sync="showIntentionState" :source="source" @closeAction="refresh"/>
    <label-com :id="collectId" :show.sync="showLabelState" :source="source" @closeAction="refresh"/>
    <source-com :id="collectId" :show.sync="showSourceState" :source="source" @closeAction="refresh"/>
    <email-add :emailsTemp="emailData" :show.sync="showBaseFormState" @closeAction="refresh"/>
    <edit :id="id" :show.sync="showState" @closeAction="refresh"/>
  </div>
</template>

<script>
import { deleteBlock, getCustomers, getExportCustomer, getList, SetIsPrivate } from '@/api/customer/block'
import { UserModule } from '@/store/modules/user'
import Pagination from '@/components/Pagination/index'
import BlockDrawer from '@/views/customer/index/blockDrawer'
import Group from '@/views/customer/common/group'
import LabelCom from '@/views/customer/common/label'
import Intention from '@/views/customer/common/intention'
import SourceCom from '@/views/customer/common/source'
import EmailAdd from '@/views/customer/index/emailAdd'
import Edit from '@/views/customer/block/edit'
import { deleteGroup } from '@/api/customer/group'
import DateSelector from '@/components/Public/dateSelector.vue'

export default {
  name: 'Block',
  components: { Pagination, Group, LabelCom, Intention, SourceCom, BlockDrawer, EmailAdd, Edit, DateSelector },
  props: {
    action: {
      type: String
    },
    tabIndex: {
      type: Number
    }
  },
  inject: ['showProgressDialog'],
  data() {
    return {
      dialogVisible: false,
      exMode: 1,
      currentUserInfo: UserModule,
      emailData: [],
      source: 'block',
      isMy: false,
      isIntention: false,
      isWater: false,
      collectId: '',
      showCustomersState: false,
      showGroupState: false,
      showIntentionState: false,
      showLabelState: false,
      showSourceState: false,
      showBaseFormState: false,
      showState: false,
      id: '',
      clientHeight: document.documentElement.clientHeight,
      clientWidth: document.documentElement.clientWidth,
      listLoading: false,
      tableHeight: 'calc(100vh - 182px)',
      list: [],
      selection: [],
      total: 0,
      listQuery: {
        limit: 20,
        page: 1,
        action: 1,
        type: '',
        name: '',
        updatedAt: []
      },
      typeOption: [
        { label: '全球搜索', value: 1 },
        { label: '数据营销', value: 2 },
        { label: '外部导入', value: 0 }
      ],
      blockId: 0,
      blockFrom: 0
    }
  },
  created() {
    this.checkTab()
  },
  mounted() {
    this.fetchData()
    window.onresize = () => {
      this.clientHeight = document.documentElement.clientHeight
      this.clientWidth = document.documentElement.clientWidth
    }
  },
  methods: {
    checkTab() {
      // 初始化
      this.isMy = false
      this.isIntention = false
      this.isWater = false
      if (this.action === 'my') {
        this.isMy = true
        this.listQuery.action = 1
      }// 我的客户
      if (this.action === 'intention') {
        this.isIntention = true
        this.listQuery.action = 2
      }// 意向客户
      if (this.action === 'water') {
        this.isWater = true
        this.listQuery.action = 3
      }//
    },
    async fetchData() {
      this.listLoading = true
      const listQuery = { ...this.listQuery }

      if (!listQuery.type) {
        delete listQuery.type
      }

      if (listQuery.updatedAt != null && listQuery.updatedAt.length != 0) {
        listQuery.updatedAtStart = listQuery.updatedAt[0] + ' 00:00:00'
        listQuery.updatedAtEnd = listQuery.updatedAt[1] + ' 23:59:59'
        delete listQuery.updatedAt
      }

      const { data } = await getList(listQuery, listQuery.page, listQuery.limit)
      this.list = data.items
      this.total = data.total
      if (this.total) {
        this.setTableHeight(315)
      } else {
        this.setTableHeight(273)
      }
      setTimeout(() => {
        this.listLoading = false
      }, 0.5 * 1000)
    },
    setTableHeight(height) {
      this.tableHeight = 'calc(100vh - ' + (height) + 'px)'
    },
    customerInfo(id, from) {
      this.blockId = id
      this.blockFrom = from
      this.showCustomersState = true
    },
    refresh() {
      // 刷新重置条件
      this.listQuery = {
        limit: 20,
        page: 1,
        action: this.listQuery.action,
        type: '',
        name: '',
        updatedAt: []
      }
      this.showCustomersState = false
      this.showGroupState = false
      this.showIntentionState = false
      this.showLabelState = false
      this.showSourceState = false
      this.showBaseFormState = false
      this.showState = false
      this.fetchData()
    },
    importCustomer() {
      const _this = this
      this.$common.ExeInvoke(function(f) {
        f.ImportClient()
      })
      this.importCallBack()
    },
    async exportData() {
      // 勾选导出
      if (this.exMode == 1) {
        if (this.selection.length <= 0) {
          this.$message({
            type: 'info',
            message: '请勾选需要批量导出的数据'
          })
          return false
        }
        const ids = []
        for (const i in this.selection) {
          ids.push(this.selection[i].id)
        }
        await getCustomers(ids).then((res) => {
          if (res.data.length) {
            const ids = []
            for (const i in res.data) {
              ids.push(res.data[i].id)
            }
            const _this = this
            this.dialogVisible = false
            this.$common.ExeInvoke(function(f) {
              f.ExportClient(ids)
              _this.exportCustomerState = false
            })
          } else {
            this.dialogVisible = false
            this.$message({
              type: 'info',
              message: '未找到相关数据'
            })
          }
        })
      }

      if (this.exMode == 2) {
        const listQuery = { ...this.listQuery }

        if (!listQuery.type) {
          delete listQuery.type
        }

        if (listQuery.updatedAt != null && listQuery.updatedAt.length != 0) {
          listQuery.updatedAtStart = listQuery.updatedAt[0] + ' 00:00:00'
          listQuery.updatedAtEnd = listQuery.updatedAt[1] + ' 23:59:59'
          delete listQuery.updatedAt
        }
        await getExportCustomer(listQuery).then((res) => {
          console.log(res)
          if (res.data.length) {
            const ids = []
            for (const i in res.data) {
              ids.push(res.data[i].id)
            }
            const _this = this
            this.dialogVisible = false
            this.$common.ExeInvoke(function(f) {
              f.ExportClient(ids)
              _this.exportCustomerState = false
            })
          } else {
            this.dialogVisible = false
            this.$message({

              type: 'info',
              message: '未找到相关数据'
            })
          }
        })
      }
    },
    openExportCustomer() {
      this.dialogVisible = true
      this.exMode = 1
    },
    search() {
      this.fetchData()
    },
    setCustomerGroupCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: '请勾选需要设置分组的数据'
        })
        return false
      }
      const ids = []
      for (const i in this.selection) {
        ids.push(this.selection[i].id)
      }
      this.collectId = ids
      this.showGroupState = true
    },
    setCustomerLabelCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: '请勾选需要设置标签的数据'
        })
        return false
      }
      const ids = []
      for (const i in this.selection) {
        ids.push(this.selection[i].id)
      }
      this.collectId = ids
      this.showLabelState = true
    },
    setCustomerSourceCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: '请勾选需要设置来源的数据'
        })
        return false
      }
      const ids = []
      for (const i in this.selection) {
        ids.push(this.selection[i].id)
      }
      this.collectId = ids
      this.showSourceState = true
    },
    handleSelection(val) {
      this.selection = val
    },
    setCustomerIsPrivateCollect(val = 0) {
      if (this.selection.length <= 0) {
        let msg = ''
        if (val == 0) {
          msg = '请勾选需要批量移入公海的客户'
        } else {
          msg = '请勾选需要批量认领的客户'
        }
        this.$message({
          type: 'info',
          message: msg
        })
        return false
      }
      const ids = []
      for (const i in this.selection) {
        ids.push(this.selection[i].id)
      }
      this.collectId = ids
      this.setCustomerIsPrivateRes(val)
    },
    setCustomerIsPrivateRes(val = 0) {
      let msg = ''
      let title = ''
      if (val == 0) {
        title = '移入'
        msg = '确认要移入公海？'
      } else {
        title = '认领'
        msg = '确认要认领？'
      }

      this.$confirm(msg, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const data = { ids: this.collectId, value: val }

        if (typeof data.ids !== 'object') {
          data.ids = [data.ids]
        }
        await SetIsPrivate(data).then((res) => {
          this.$notify({
            title: '成功',
            message: `${title}成功`,
            type: 'success',
            duration: 2000
          })
          this.fetchData()
        })
      })
    },
    setCustomerIntentionCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: '请勾选需要批量更新意向状态'
        })
        return false
      }
      const ids = []
      for (const i in this.selection) {
        ids.push(this.selection[i].id)
      }
      this.collectId = ids
      this.showIntentionState = true
    },
    batchDeleteBlock() {
      if (this.selection.length <= 0) {
        this.$message('请选择需要批量删除的数据')
        return false
      }
      const uploadItems = [
        { name: '数据', num: this.selection.length, action: this.batchDeleteFunc, data: this.selection }
      ]
      const uploadColumns = [
        { label: '标题', key: 'name', popover: true }
      ]
      this.showProgressDialog(uploadItems, uploadColumns, this.refresh, { title: '批量删除，此操作不可逆' })
    },
    async batchDeleteFunc({ item, message }) {
      await deleteBlock({ id: item.id, type: this.tabIndex }).then(() => {
        message.success('[' + item.name + '] 删除成功')
      }).catch((res) => {
        message.failed('[' + item.name + '] ' + res.message)
      })
    },
    async setCustomerEmailCollect() {
      if (this.selection.length <= 0) {
        this.$message({
          type: 'info',
          message: '请勾选需要批量新增营销任务'
        })
        return false
      }
      const ids = []
      for (const i in this.selection) {
        ids.push(this.selection[i].id)
      }
      await getCustomers(ids).then((res) => {
        this.emailData = res.data
        if (this.emailData.length) {
          this.showBaseFormState = true
        } else {
          this.$message({
            type: 'info',
            message: '未找到相关邮箱'
          })
        }
      })
    },
    addRow() {
      this.id = ''
      this.showState = true
    },
    editRow(id) {
      this.id = id
      this.showState = true
    },
    downloadExportTemplate() {
      window.open('/api/download/import')
    },
    deleteRow(id) {
      this.$confirm('确认要删除吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        this.listLoading = true
        await deleteBlock({ id: id, type: this.tabIndex }).then((res) => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.fetchData()
        })
      }).catch(() => {
        this.fetchData()
      })
    }
  }
}
</script>

<style scoped>
.customer /deep/ .el-divider--horizontal {
  margin: 5px 0 !important;
}
</style>
